home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sun, 21 Jan 1996 22:10:10 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601212110.AA19771@dxmint.cern.ch>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <9601201820.AA01752@dxmint.cern.ch> <4dtqpq$sl2@oxy.rust.net>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- ebennett@rust.net writes:
-
- >Dan Pop <danpop@mail.cern.ch> wrote:
- >
- >>ebennett@rust.net writes:
- >
- >>>Given some number, there is a neat trick to generate a mask which will
- >>>have exactly one bit set in it. The bit set will be the least
- >>>significant non-zero bit in the original number:
- >>>
- >>> mask = ~number & number;
- ^
- >>>
- >>>Now, if number contained a single non-zero bit (and is therefore a
- >>>power of 2), mask will be equal to number. Therefore:
- >>>
- >>> if (number == (~number & number))
- ^
- >>> {
- >>> /* number is a power of 2 */
- >>> }
- >>>
- >>>Try it, you'll like it!
- >
- >>I don't think so. ~number & number will _always_ give 0. -number & number
- >>will actually work, except for the case when number == 0. That is,
- >>assuming a two's complement implementation. On a one's complement or
- >>sign-magnitude implementation it won't work at all.
- >
- >>Yet another guy who makes a fool of himself because he's too lazy to
- >>test his solution before posting.
- >
- >You are correct in that I made a typo in my message. ~ should have
- >been -.
-
- It was NOT a typo, because you wrote ~ instead of - consistently, not in a
- single place.
-
- >Where would you run into a one's complement or sign-magnitude
- >implementation?
-
- These implementations are allowed by the C standard and there are people
- who actually ran into them. When posting a solution to c.l.c you have to
- either consider all possible situations or document its limitations.
- Otherwise, someone else will do it :-)
-
- >However, I do not feel that I made a fool of myself. Most of us are
- >not perfect as you apparently are. The rest of us make mistakes, and
- >learn from them. That does not make us fools.
-
- Making mistakes doesn't make one a fool. Posting mistakes which could have
- been easily detected by actually testing the proposed solution does make
- one a fool. The difference between a smart guy and fool guy making the
- same mistake is that the smart one can discover it himself.
-
- Nobody is perfect, but checking your advice with your compiler and your
- ANSI C reference book before posting will make you look almost perfect :-)
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-